import { defineStore } from 'pinia'
import { login, logout, getUserInfo } from '@/api/user'
import { ref, computed } from 'vue'

export interface UserState {
  username: string
  userId: number
  name: string
  roleList: string[]
  isLogin: boolean
}

export const useUserStore = defineStore('user', () => {
  const user = ref<UserState>({
    username: '',
    userId: 0,
    name: '',
    roleList: [],
    isLogin: false
  })

  const isLoggedIn = computed(() => user.value.isLogin)
  const hasRole = (role: string) => user.value.roleList[0] === role
  const userLogin = async (credentials: { username: string; password: string }) => {
    const res = await login(credentials)
    if (!res?.data) {
      throw new Error('登录失败')
    }

    const userInfo = await getUserInfo()
    if (!userInfo?.data) {
      throw new Error('获取用户信息失败')
    }

    user.value = {
      username: userInfo.data.username,
      userId: userInfo.data.userId,
      name: userInfo.data.name,
      roleList: userInfo.data.roleList,
      isLogin: true
    }
  }

  const userLogout = async () => {
    await logout()
    user.value = {
      username: '',
      userId: 0,
      name: '',
      roleList: [],
      isLogin: false
    }
  }

  return { user, isLoggedIn, hasRole, userLogin, userLogout }
})
